<template>
  <div>
    <!-- <div class="toptitle">组织编码</div> -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline" @keyup.enter.native="search()">

      <el-form-item label="大区名称">
        <br> <br>
        <el-input v-model="formInline.upOrgZone" placeholder style="margin-left:-60px;width:200px"></el-input>
      </el-form-item>

      <el-form-item label="营销区域名称">
        <br> <br>
        <el-input v-model="formInline.baseName" placeholder style="margin-left:-60px;width:200px" ></el-input>
      </el-form-item>

      <el-form-item label="店铺授权编码">
        <br> <br>
        <el-input v-model="formInline.authCode" placeholder style="margin-left:-80px;width:200px"></el-input>
      </el-form-item>

      <el-form-item label="店铺名称">
        <br> <br>
        <el-input v-model="formInline.storeName" placeholder style="margin-left:-60px;width:200px" ></el-input>
      </el-form-item>

      <div class="block" >
        <span class="demonstration" style="    text-align: right;
    float: left;
    font-size: 12px;
    color: #606266;
    line-height: 40px;
    padding: 0 12px 0 0;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;">选择时间</span>
    <br><br>

    <el-date-picker
       v-model="value4"
       type="daterange"
       align="right"
       unlink-panels
       range-separator="至"
       start-placeholder="开始日期"
       end-placeholder="结束日期"
       value-format="yyyy-MM-dd"
       :picker-options="pickerOptions2">
     </el-date-picker>

      <!--  <el-date-picker v-model="value4" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions2"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right" style="width:410px">
        </el-date-picker> -->

      </div>

      <el-form-item style="margin-left:800px;text-align:right;margin-top:10px;margin-bottom:20px">
        <el-button type="primary" @click="searchData()" size="mini" icon="el-icon-search">查询</el-button>

        <el-button type="primary" @click="kong()" size="mini" icon="el-icon-delete">重置</el-button>

        <el-button type="success" @click="exportExcel()" size="mini" icon="el-icon-s-data">导出</el-button>

        <el-button type="primary" @click="showConfigTableDialog()" size="mini" :loading="insertLoading" icon="el-icon-setting">列表配置</el-button>
      </el-form-item>
      <!--列表配置
           列表配置列 需要绑定sishow属性  是否展示
        -->
      <el-dialog title="列表配置" :visible.sync="configTableDialogVisible" width="50%" @close="closeConfigTableDialog()">
        <div id="configTableDiv">
          <el-form :inline="true" :model="formInline2" class="demo-form-inline">
            <el-form-item label="选择列表字段：">
              <el-checkbox :indeterminate="formInline2.isIndeterminate" v-model="formInline2.isAll" style="margin-top:10px;"
                @change="isAllFieldChange">全选</el-checkbox>
            </el-form-item>

            <el-divider></el-divider>
            <el-checkbox-group v-model="userMenuShowFields" @change="isSingleFieldChange">
              <el-checkbox v-for="item in userMenuFieldList" :label="item.fieldCode" :key="item.fieldCode" style="margin:15px 10px;width:120px;">{{item.fieldName}}</el-checkbox>
            </el-checkbox-group>
          </el-form>
          <el-row>
            <el-col :span="24" style="text-align: center;margin-top: 30px">
              <el-button type="info" @click="closeConfigTableDialog()" size="mini">取 消</el-button>
              <el-button type="primary" @click="insertUserFieldRelation()" size="mini">确 认</el-button>
            </el-col>
          </el-row>
        </div>
      </el-dialog>
    </el-form>
    <!-- 列表配置 -->

    </el-form>
    <el-table :data="tableData" :header-cell-style="{background:'#eef1f6',color:'#606266'}" style="width: 100%;margin-bottom: 20px;"
      row-key="goodsTypeId" border v-loading="loading" default-expand-all @sort-change="handleSort">
      <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
      <el-table-column prop="upOrgZone" show-overflow-tooltip
      v-if="isShow('upOrgZone')"  label="大区名称" width="160" align="center"></el-table-column>

      <el-table-column prop="baseName" show-overflow-tooltip
      v-if="isShow('baseName')"  label="营销区域名称" align="center" width="150"></el-table-column>

      <el-table-column prop="companyName" show-overflow-tooltip
      v-if="isShow('companyName')"  label="经销商名称" width="180" align="center"></el-table-column>

      <el-table-column prop="authCode" show-overflow-tooltip
      v-if="isShow('authCode')"  label="店铺授权码" align="center" width="180"></el-table-column>

      <el-table-column prop="storeName" show-overflow-tooltip
      v-if="isShow('storeName')"  label="店铺名称" width="180" align="center"></el-table-column>

      <el-table-column prop="accumulatedSellCount" show-overflow-tooltip
      v-if="isShow('accumulatedSellCount')"  label="累计销售数量（瓶）" align="center" width="180" sortable="accumulatedSellCount">
      <template slot="header" slot-scope="scope">
        <span>累计销售数量（瓶）
          <el-popover placement="top-start" width="200" trigger="hover" content="XX店铺已付款订单所含商品数量（瓶）（包含已退款订单）">
            <el-button slot="reference" @click.stop style="padding:0;border:0"><i class="el-icon-question"></i></el-button>
          </el-popover>
        </span>
      </template>
      </el-table-column>

      <el-table-column prop="accumulatedSellCountPercentage" show-overflow-tooltip
      v-if="isShow('accumulatedSellCountPercentage')"  label="累计销售数量占比（%）" width="180" align="center">
      <template slot="header" slot-scope="scope">
        <span>累计销售数量占比（%）
          <el-popover placement="top-start" width="200" trigger="hover" content="XX店铺已付款订单所含商品数量/全部店铺已付款订单所含商品数量*100％">
            <el-button slot="reference" @click.stop style="padding:0;border:0"><i class="el-icon-question"></i></el-button>
          </el-popover>
        </span>
      </template></el-table-column>

      <el-table-column prop="accumulatedPaymentMoney" show-overflow-tooltip
      v-if="isShow('accumulatedPaymentMoney')"  label="累计付款金额（元）" align="center" width="180" sortable="accumulatedPaymentMoney">
      <template slot="header" slot-scope="scope">
        <span>累计付款金额（元）
          <el-popover placement="top-start" width="200" trigger="hover" content="XX店铺已付款订单累计金额（包含已退款订单累计金额）">
            <el-button slot="reference" @click.stop style="padding:0;border:0"><i class="el-icon-question"></i></el-button>
          </el-popover>
        </span>
      </template></el-table-column>

      <el-table-column prop="accumulatedPaymentMoneyPercentage" show-overflow-tooltip
      v-if="isShow('accumulatedPaymentMoneyPercentage')"  label="累计付款金额占比（%）" align="center" width="180">
      <template slot="header" slot-scope="scope">
        <span>累计付款金额占比（%）
          <el-popover placement="top-start" width="200" trigger="hover" content="XX店铺已付款订单累计金额/全部店铺已付款订单金额*100％">
            <el-button slot="reference" @click.stop style="padding:0;border:0"><i class="el-icon-question"></i></el-button>
          </el-popover>
        </span>
      </template></el-table-column>

      <el-table-column prop="accumulativeStandardProduct" label="累计标品成交金额（元）" align="center" width="180">
        <template slot-scope="scope">
          {{ scope.row.accumulativeStandardProduct || 0 }}
        </template>
      </el-table-column>

      <el-table-column prop="accumulatedRefundMoney" show-overflow-tooltip
      v-if="isShow('accumulatedRefundMoney')"  label="累计退款金额（元）" align="center" width="180" sortable="accumulatedRefundMoney">
      <template slot="header" slot-scope="scope">
        <span>累计退款金额（元）
          <el-popover placement="top-start" width="200" trigger="hover" content="XX店铺已退款订单累计金额">
            <el-button slot="reference" @click.stop style="padding:0;border:0"><i class="el-icon-question"></i></el-button>
          </el-popover>
        </span>
      </template></el-table-column>

      <el-table-column prop="accumulatedRefundMoneyPercentage" show-overflow-tooltip
      v-if="isShow('accumulatedRefundMoneyPercentage')"  label="累计退款金额占比（%）" align="center" width="180">
      <template slot="header" slot-scope="scope">
        <span>累计退款金额占比（%）
          <el-popover placement="top-start" width="200" trigger="hover" content="XX店铺已退款订单累计金额/全部店铺已退款订单累计金额*100％">
            <el-button slot="reference" @click.stop style="padding:0;border:0"><i class="el-icon-question"></i></el-button>
          </el-popover>
        </span>
      </template></el-table-column>

      <el-table-column prop="accumulatedAccomplishMoney" show-overflow-tooltip
      v-if="isShow('accumulatedAccomplishMoney')"  label="累计成交金额（元）" align="center" width="180" sortable="accumulatedAccomplishMoney">
      <template slot="header" slot-scope="scope">
        <span>累计成交金额（元）
          <el-popover placement="top-start" width="200" trigger="hover" content="XX店铺已完成订单累计金额">
            <el-button slot="reference" @click.stop style="padding:0;border:0"><i class="el-icon-question"></i></el-button>
          </el-popover>
        </span>
      </template></el-table-column>

      <el-table-column prop="accumulatedAccomplishMoneyPercentage" show-overflow-tooltip
      v-if="isShow('accumulatedAccomplishMoneyPercentage')"  label="累计成交金额占比（%）" align="center" width="180">
      <template slot="header" slot-scope="scope">
        <span>累计成交金额占比（%）
          <el-popover placement="top-start" width="200" trigger="hover" content="XX店铺已完成订单金额/全部店铺已完成订单累计金额*100％">
            <el-button slot="reference" @click.stop style="padding:0;border:0"><i class="el-icon-question"></i></el-button>
          </el-popover>
        </span>
      </template></el-table-column>

      <el-table-column prop="memberPaymentCount" show-overflow-tooltip
      v-if="isShow('memberPaymentCount')"  label="会员付款人数（人）" align="center" width="180" sortable="memberPaymentCount">
      <template slot="header" slot-scope="scope">
        <span>会员付款人数（人）
          <el-popover placement="top-start" width="200" trigger="hover" content="X店铺已付款会员人数（包含已退款会员人数）">
            <el-button slot="reference" @click.stop style="padding:0;border:0"><i class="el-icon-question"></i></el-button>
          </el-popover>
        </span>
      </template></el-table-column>

      <el-table-column prop="memberPaymentAvg" show-overflow-tooltip
      v-if="isShow('memberPaymentAvg')"  label="会员人均付款金额（元）" align="center" width="200" sortable="memberPaymentAvg">
      <template slot="header" slot-scope="scope">
        <span>会员人均付款金额（元）
          <el-popover placement="top-start" width="200" trigger="hover" content="XX店铺内的累计付款金额/会员付款人数">
            <el-button slot="reference" @click.stop style="padding:0;border:0"><i class="el-icon-question"></i></el-button>
          </el-popover>
        </span>
      </template></el-table-column>

    </el-table>
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.current"
        :page-sizes="[10, 20, 30, 50, 100, 150, 200]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

  </div>
</template>

<script>
  import {
    queryStoreSellStatement,
    exportStoreSellStatement
  } from "@/api/storeSellStatement";
  import {
    queryUserMenuFieldByParam,
    insertUserFieldRelation
  } from "@/api/tradeOrderSearch";
  import qs from "qs";
  export default {
    data() {
      return {
        pickerOptions2: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        value4: [],
        headers: {
          token: localStorage.getItem("token"), //从cookie里获取token，并赋值  Authorization ，而不是token
        },
        tableData: [],
        listQuery: {
          current: 1,
          size: 10
        },
        logininfo: "",
        orgList: "",
        formInline: {
          ascs: [],
          descs: [],
          upOrgZone: "",
          baseName: "",
          authCode: "",
          storeName: ""
        },
        loading: false,
        total: 0,
        /*
          列表配置全部属性
          ----------------------------------------
          --------------start---------------------
        */
        configTableDialogVisible: false, //列表配置弹窗状态
        formInline2: {
          isIndeterminate: false, //是否选中
          isAll: true, //是否全部显示,
          menuCode: "queryStoreSellStatement"
        },
        userMenuShowFields: [], //显示的列名
        userMenuFieldList: [], //全部列名列表
        insertLoading: false,
        /*
          列表配置全部属性
          ----------------------------------------
          -------------end------------------
        */
      };
    },
    mounted() {
      /*  列表配置
       */
      this.queryUserMenuFieldByParam();
      /*  列表配置
       */
      this.logininfo = localStorage.getItem("logininfo");
      this.orgList = JSON.parse(this.logininfo).orgList;
      this.search();
    },
    methods: {
      //排序
      handleSort(val) {

        //排序之前将页码重置为1
        this.listQuery.current = 1;
        this.formInline.descs = [];
        this.formInline.ascs = [];
        let sortModel = "";
        if (val.order === "ascending") {
          sortModel = "ASC";
          this.formInline.ascs = [val.column.sortable];
          this.formInline.descs = [];
          this.search();
        } else if (val.order === "descending") {
          sortModel = "DESC";
          this.formInline.ascs = [];
          this.formInline.descs = [val.column.sortable];
          this.search();
        }
      },
      // 重置页码查询 查询
      searchData() {
        this.listQuery.current = 1;
        this.search();
      },
      //查询
      search() {
        this.loading = true;
        let data = {
          size: this.listQuery.size,
          current: this.listQuery.current,
          condition: {
            startTime: !this.value4 ? "" : this.value4.length == 0 ? "" : this.value4[0]+" 00:00:00",
            endTime: !this.value4 ? "" : this.value4.length == 0 ? "" : this.value4[1]+" 23:59:59",
            orgSeq: this.orgList[0].orgSeq,
            upOrgZone: this.formInline.upOrgZone,
            baseName: this.formInline.baseName,
            authCode: this.formInline.authCode,
            storeName: this.formInline.storeName
          },
          ascs: this.formInline.ascs,
          descs: this.formInline.descs
        };
        queryStoreSellStatement(data).then(res => {
          this.total = res.total;
          this.tableData = res.records;
          this.loading = false;
        });
      },
      handleCurrentChange(val) {
        this.listQuery.current = val;
        this.search();
      },
      handleSizeChange(val) {
        this.listQuery.size = val;
        this.search();
      },
      //导出
      exportExcel() {
        let data = {
          size: this.listQuery.size,
          current: this.listQuery.current,
          condition: {
            startTime: !this.value4 ? "" : this.value4.length == 0 ? "" : this.value4[0]+" 00:00:00",
            endTime: !this.value4 ? "" : this.value4.length == 0 ? "" : this.value4[1]+" 23:59:59",
            orgSeq: this.orgList[0].orgSeq,
            upOrgZone: this.formInline.upOrgZone,
            baseName: this.formInline.baseName,
            authCode: this.formInline.authCode,
            storeName: this.formInline.storeName
          },
          ascs: this.formInline.ascs,
          descs: this.formInline.descs
        }
        exportStoreSellStatement(data)
          .then(res => {
            const link = document.createElement("a");
            let blob = new Blob([res], {
              type: "application/vnd.ms-excel"
            });
            link.style.display = "none";
            //设置连接
            link.href = URL.createObjectURL(blob);
            link.download = "店铺销售报表（" + this.orgList[0].orgName + "）.xlsx";
            document.body.appendChild(link);
            //模拟点击事件
            link.click();
          })
          .catch(err => {
            console.log(err);
          });
      },
      kong() {
        this.value4 = "";
        this.formInline.upOrgZone = "";
        this.formInline.baseName = "";
        this.formInline.authCode = "";
        this.formInline.storeName = "";
      },
      /*
        --------------------------------------------------------
        ----------------------列表配置全部代码--------------------
        -------------------------start---------------------------
      */
      //关闭配置弹窗
      closeConfigTableDialog() {
        this.queryUserMenuFieldByParam();
        this.configTableDialogVisible = false;
      },
      //获取列表字段列表
      queryUserMenuFieldByParam() {
        let data = {
          menuCode: this.formInline2.menuCode
        };
        this.userMenuAllFields = []; //全部的列名
        this.userMenuShowFields = []; //显示的列名
        queryUserMenuFieldByParam(data).then(res => {
          this.userMenuFieldList = res.records;
          this.userMenuFieldList.forEach((item, index) => {
            this.userMenuAllFields.push(item.fieldCode);
            if (item.isShow == 1) {
              this.userMenuShowFields.push(item.fieldCode);
            }
          });
          if (this.userMenuShowFields.length == 0 || this.userMenuShowFields.length == this.userMenuAllFields.length) {
            this.userMenuShowFields = this.userMenuAllFields;
            this.formInline2.isAll = true;
          } else {
            this.formInline2.isAll = false;
            this.formInline2.isIndeterminate = true;
          }
        });
      },
      //是否全选字段
      isAllFieldChange(val) {
        this.userMenuShowFields = val ? this.userMenuAllFields : [];
        this.formInline2.isIndeterminate = false;
      },
      //是否选中单个字段
      isSingleFieldChange(val) {
        let checkedCount = this.userMenuShowFields.length;
        this.formInline2.isAll = checkedCount === this.userMenuAllFields.length;
        this.formInline2.isIndeterminate = checkedCount > 0 && checkedCount < this.userMenuAllFields.length;
      },
      //保存显示字段
      insertUserFieldRelation() {
        if (this.userMenuShowFields == null || this.userMenuShowFields.length == 0) {
          this.$message({
            showClose: true,
            message: "列表字段不可为空",
            type: "info"
          });
          return;
        }
        let data = {
          menuCode: this.formInline2.menuCode,
          fieldList: this.userMenuShowFields
        };
        this.insertLoading = true;
        insertUserFieldRelation(data).then(res => {
          this.insertLoading = false;
          if (res.code == 1) {
            this.$message({
              showClose: true,
              message: res.message,
              type: "success"
            });
            this.closeConfigTableDialog();
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: "error"
            });
          }
        });
      },
      //显示配置弹窗
      showConfigTableDialog() {
        this.configTableDialogVisible = true;
      },
      //是否显示字段
      isShow(fieldCode) {
        if (this.formInline2.isAll || this.getUserMenuFieldStatus(fieldCode)) {
          return true;
        } else {
          return false;
        }
      },
      //获取字段勾选状态
      getUserMenuFieldStatus(fieldCode){
        if(this.userMenuShowFields != null){
          for (let i = 0; i < this.userMenuShowFields.length; i++) {
            if(this.userMenuShowFields[i] == fieldCode){
              return true;
            }
          }
          return false;
        }
      },

      /*
      --------------------------------------------
      ---------------列表配置全部代码---------------
      ---------------------end--------------------
      */

    }
  };
</script>
<style lang="less" scoped>
  .toptitle {
    border: 1px solid #e0e0e0;
    border-bottom: 2px solid #188097;
    background: #f5f5f5;
    line-height: 35px;
    margin-bottom: 10px;
    padding: 0 10px;
    font-size: 14px;
    font-weight: bold;
  }

  .el-form-item .el-select {
    width: 100%;
  }
</style>
